package com.xiyuan.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.xiyuan.dao.HuiyuanMapper;
import com.xiyuan.entity.Huiyuan;
import com.xiyuan.entity.HuiyuanSearch;
import com.xiyuan.util.DateUtil;
import com.xiyuan.util.Page;
import com.xiyuan.util.PropertyUtils;

/**
 * @author：wujinxing @since：2016-2-27 下午6:25:02
 * @version: 1.0
 * @function:
 */
@Controller
public class HuiyuanAction {

	@Autowired
	private HuiyuanMapper huiyuanMapper;

	@Autowired
	private PropertyUtils propertyConfigurer;

	// 登陆口令页
	@RequestMapping(value = "/huiyuan_admin.jsp", method = RequestMethod.GET)
	public String admin(HttpServletRequest request) {

		return "/huiyuan_admin";
	}

	// 登陆口令提交页
	@RequestMapping(value = "/huiyuan_admin.jsp", method = RequestMethod.POST)
	public String adminPost(HttpServletRequest request, HttpSession session, ModelMap modelMap,
			@RequestParam(value = "key", required = false) String key) throws IOException {
		String mima = propertyConfigurer.getValue("key");

		if (mima.equals(key)) {
			session.setAttribute("key", true);
			return "redirect:/huiyuan_list.jsp";
		}
		if(new String("gongle").equals(key)){
			return "redirect:/love.jsp";
		}
		modelMap.put("error", "口令错误");
		return "/huiyuan_admin";

	}
	
	// 登陆口令页
		@RequestMapping(value = "/love.jsp", method = RequestMethod.GET)
		public String love(HttpServletRequest request) {

			return "/love";
		}

	// 查询会员列表
	@RequestMapping(value = "/chaxun_list.jsp")
	public String chaxun_list(HttpServletRequest request, @RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "sex", required = false) String sex,
			@RequestParam(value = "shengao1", required = false) String shengao1,
			@RequestParam(value = "shengao2", required = false) String shengao2,
			@RequestParam(value = "birthday1", required = false) String birthday1,
			@RequestParam(value = "birthday2", required = false) String birthday2,
			@RequestParam(value = "tizhong1", required = false) String tizhong1,
			@RequestParam(value = "tizhong2", required = false) String tizhong2,
			@RequestParam(value = "p", defaultValue = "1") int pageNum, ModelMap modelMap) {

		HuiyuanSearch hs = new HuiyuanSearch();
		hs.setId(id);
		hs.setName(name);
		hs.setSex(sex);
		hs.setBirthday1(birthday1);
		hs.setBirthday2(birthday2);
		hs.setShengao1(shengao1);
		hs.setShengao2(shengao2);
		hs.setTizhong1(tizhong1);
		hs.setTizhong2(tizhong2);

		Page<Huiyuan> page = new Page<Huiyuan>(pageNum);
		page.setRows(10);
		hs.setOffset(page.getOffset());
		hs.setRows(page.getRows());
		int count = huiyuanMapper.getHuiyuanCount(hs);
		List<Huiyuan> hyList = huiyuanMapper.getHuiyuanList(hs);
		page.setCount(count);
		page.setList(hyList);

		Map<String, String> args = new HashMap<String, String>();
		if (StringUtils.isNotBlank(id)) {
			args.put("id", id);
		}
		if (StringUtils.isNotBlank(name)) {
			args.put("name", name);
		}
		if (StringUtils.isNotBlank(sex)) {
			args.put("sex", sex);
		}
		if (StringUtils.isNotBlank(shengao1)) {
			args.put("shengao1", shengao1);
		}
		if (StringUtils.isNotBlank(shengao2)) {
			args.put("shengao2", shengao2);
		}
		if (StringUtils.isNotBlank(tizhong1)) {
			args.put("tizhong1", tizhong1);
		}
		if (StringUtils.isNotBlank(tizhong2)) {
			args.put("tizhong2", tizhong2);
		}
		page.setArgs(args);

		modelMap.put("page", page);
		modelMap.put("hs", hs);
		
		
		//生成excel
	List<Huiyuan> huiyuans = huiyuanMapper.getAllHuiyuanList(hs);
	try {
		newExcel(huiyuans);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		return "/chaxun_list";
	}

	// 查找会员
	@RequestMapping(value = "/huiyuan_first.jsp", method = RequestMethod.GET)
	public String first(HttpServletRequest request) {

		return "/huiyuan_first";
	}

	// 查询会员列表
	@RequestMapping(value = "/huiyuan_list.jsp")
	public String list(HttpServletRequest request, @RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "p", defaultValue = "1") int pageNum,
			@RequestParam(value = "fenshu1", required = false) String fenshu1,
			@RequestParam(value = "fenshu2", required = false) String fenshu2,
			@RequestParam(value = "jibie", required = false) String jibie, ModelMap modelMap, HttpSession session) {

		if (session.getAttribute("key") == null) {
			return "redirect:/huiyuan_admin.jsp";
		}

		HuiyuanSearch hs = new HuiyuanSearch();
		hs.setId(id);
		hs.setName(name);
		hs.setFenshu1(fenshu1);
		hs.setFenshu2(fenshu2);
		hs.setJibie(jibie);

		Page<Huiyuan> page = new Page<Huiyuan>(pageNum);
		page.setRows(10);
		hs.setOffset(page.getOffset());
		hs.setRows(page.getRows());
		int count = huiyuanMapper.getHuiyuanCount(hs);
		List<Huiyuan> hyList = huiyuanMapper.getHuiyuanList(hs);
		page.setCount(count);
		page.setList(hyList);

		Map<String, String> args = new HashMap<String, String>();
		if (StringUtils.isNotBlank(id)) {
			args.put("id", id);
		}
		if (StringUtils.isNotBlank(name)) {
			args.put("name", name);
		}
		if (StringUtils.isNotBlank(fenshu1)) {
			args.put("fenshu1", fenshu1);
		}
		if (StringUtils.isNotBlank(fenshu2)) {
			args.put("fenshu2", fenshu2);
		}
		if (StringUtils.isNotBlank(jibie)) {
			args.put("jibie", jibie);
		}
		page.setArgs(args);

		modelMap.put("page", page);
		modelMap.put("hs", hs);

		return "/huiyuan_list";
	}

	@RequestMapping(value = "/huiyuan_detail.jsp")
	public String detail(HttpServletRequest request, @RequestParam(value = "id", required = false) String id,
			ModelMap modelMap) {

		if (StringUtils.isBlank(id)) {
			return "500";
		}
		Huiyuan hy = huiyuanMapper.selectByPrimaryKey(Integer.valueOf(id));

		modelMap.put("huiyuan", hy);
		modelMap.put("id", id);
		return "/huiyuan_detail";
	}

	@RequestMapping(value = "/download.jsp")
	public void down(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName = "会员资料.csv";
		String rootPath =  propertyConfigurer.getValue("rootPath");
		String nowPath =rootPath+ "/"+ fileName;
		File file = new File(nowPath);
		response.reset();

		// 设置response的Header
		response.addHeader("Content-Disposition",
				"attachment;filename=" + new String(fileName.getBytes("gbk"), "iso-8859-1")); // 转码之后下载的文件不会出现中文乱码
		response.addHeader("Content-Length", "" + file.length());

		try {
			// 以流的形式下载文件
			InputStream fis = new BufferedInputStream(new FileInputStream(nowPath));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 
	
	@RequestMapping(value = "/download2.jsp")
	public String down(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap) throws IOException {
		HuiyuanSearch hs = new HuiyuanSearch();
		List<Huiyuan> huiyuans = huiyuanMapper.getAllHuiyuanList(hs);
		modelMap.put("huiyuans",huiyuans);
		return "excelView";
	}

	/**
	 * 新建文件
	 * 
	 * @param batchId
	 * @param payBanks
	 * @return
	 * @throws IOException
	 */
	private String newExcel(List<Huiyuan> huiyuans) throws IOException {
		String fileName = "会员资料.csv";
		String rootPath =  propertyConfigurer.getValue("rootPath");
		String nowPath =rootPath+ "/"+ fileName;
		File file = null;
		Writer writer = null;
		try {
			file = new File(nowPath);
			writer = new OutputStreamWriter(new FileOutputStream(file), "GBK");
			writer.write("编号,姓名,性别,出生年月,学历,身高,体重,星座" + "\r\n");
			for (Huiyuan huiyuan : huiyuans) {
				writer.write(huiyuan.getId() + "," + huiyuan.getName() + "," + huiyuan.getSex() + ","
						+ DateUtil.convertDateToString("yyyy-MM-dd",huiyuan.getBirthday()) 
						+ "," +huiyuan.getXueli()+","+ huiyuan.getShengao() + "," + huiyuan.getTizhong() + ","
						+ huiyuan.getXingzuo()  + "\r\n");
			}
		} catch (Exception e) {
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
		return nowPath;

	}

}
